package com.cos.hospital.ui.record.edit;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.CacheDiskUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cos.hospital.R;
import com.cos.hospital.code.BedType;
import com.cos.hospital.code.Code;
import com.cos.hospital.code.helper.KTextWatcher;
import com.cos.hospital.dao.HelperAcuDb;
import com.cos.hospital.dao.beandao.DbAcupoint;
import com.cos.hospital.init.App;
import com.cos.hospital.model.UHttp;
import com.cos.hospital.model.bean.AcupointBean;
import com.cos.hospital.model.bean.BedBean;
import com.cos.hospital.model.bean.CureInfo;
import com.cos.hospital.model.bean.ErrorBean;
import com.cos.hospital.model.bean.PatientListBean;
import com.cos.hospital.model.bean.RecordWebBean;
import com.cos.hospital.model.bean.ResultBean;
import com.cos.hospital.model.connector.HttpMsgListener;
import com.cos.hospital.model.retrofit.MyObserver;
import com.cos.hospital.tool.MyUtil;
import com.cos.hospital.tool.SPUtil;
import com.cos.hospital.tool.UDate;
import com.cos.hospital.tool.UDialog;
import com.cos.hospital.tool.UKeyboard;
import com.cos.hospital.tool.UToast;
import com.cos.hospital.tool.UTxt;
import com.cos.hospital.ui.main.MainActivity;
import com.cos.hospital.ui.patient.SurplusCureActivity;
import com.cos.hospital.ui.record.RecordBaseActivity;
import com.cos.hospital.ui.record.RecordEditActivity;
import com.cos.hospital.ui.record.adapter.AdapterAcupoint;
import com.cos.hospital.ui.record.adapter.AdapterAuto;
import com.cos.hospital.ui.record.adapter.BedAdapter;
import com.cos.hospital.widget.KKeyboardView;
import com.cos.hospital.widget.MyDividerDecoration;
import com.cos.hospital.widget.MyGridLayoutManager;
import com.cos.hospital.widget.MySpaceDecoration;
import com.cos.hospital.widget.ProgressDialog;
import com.cos.hospital.widget.baseadapter.OnRecyclerViewListener;
import com.cos.hospital.widget.seekbar.KBubbleSeekBar;
import com.google.gson.JsonObject;
import com.jude.utils.JUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @Description: 编辑:针灸方案
 * @Author: Kosmos yby
 * @Date: 2018年09月23日 20:52
 * @Email: KosmoSakura@foxmail.com
 */
public class EditorAcupointActivity extends RecordBaseActivity implements View.OnTouchListener {

    public static final String DATA_LIST_KEY = "DATA_LIST_KEY";

    private final int FunAcuHide = 0;
    private final int FunAcu = 1;
    private final int FunAcuOthers = 2;
    private final int FunAcuBoth = 3;
    private final int FunAcuVoice = 4;
    private final int what_code = 9010;
    @BindView(R.id.rec_acu_root_lay)
    View rootLay;
    @BindView(R.id.rec_acu_count)
    TextView tCont;//治疗针数
    @BindView(R.id.rec_acu_time_remaining)
    TextView tTimeRemaining;//剩余时长
    @BindView(R.id.tv_total_time)
    TextView tv_total_time;//总时长
    @BindView(R.id.tv_surplus_count)
    TextView tv_surplus_count;//剩余针灸次数
    @BindView(R.id.rec_acu_sb)
    KBubbleSeekBar seekBar;//剩余时长
    @BindView(R.id.iv_start)
    ImageView iv_start;//开始治疗
    @BindView(R.id.tv_previous)
    TextView tv_previous;//上一个病人
    @BindView(R.id.tv_next)
    TextView tv_next;//下一个病人
    @BindView(R.id.lay_rec_fun_lay)
    View layFunction;//工具区域
    @BindView(R.id.lay_auto)
    View lay_auto;//穴位选择区
    @BindView(R.id.rec_acu_rc)
    RecyclerView rc;//穴位列表
    @BindView(R.id.rec_acu_auto_rc)
    RecyclerView autoRc;//穴位列表
    @BindView(R.id.lay_rec_fun_result)
    EditText autoEdt;
    @BindView(R.id.keyboard)
    KKeyboardView keyboardView;
    @BindView(R.id.bed)
    RecyclerView bedRec;
    @BindView(R.id.other_text)
    EditText other_text;
    List<BedBean> bedBeans;
    private AdapterAuto autoAdapter;
    private BedAdapter bedAdapter;
    private List<DbAcupoint> autoList;
    private List<AcupointBean> listAcup;
    private AdapterAcupoint adapterAcup;
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == what_code) {
                String key = autoEdt.getText().toString();
                if (UTxt.isEmpty(key)) {
                    autoList.clear();
                    autoAdapter.notifyDataSetChanged();
                } else {
                    List<DbAcupoint> list = HelperAcuDb.SearchBlurry(context, key);
                    if (UTxt.isEmpty(list)) {
                        autoList.clear();
                        autoAdapter.notifyDataSetChanged();
                    } else {
                        autoList.clear();
                        autoList.addAll(list);
                        autoAdapter.notifyDataSetChanged();
                    }
                }
            }
            return false;
        }
    });
    private int acupointNumber;
    private boolean editAcupoint;
    private long delta;//已过时长（分钟）
    private boolean cureing;//是否正在治疗（本地）
    private int fldTreatmentDuration;//治疗时长
    private int fldTreatmentDuration_old;
    private Disposable disposable;
    private int fldTotalDuration;

    @Override
    protected int layout() {
        return R.layout.activity_editor_acupoint;
    }

    @Override
    protected void initData() {
        setTitleLeftIcon();
        setTitleRightTxt(getString(R.string.save));
        setTitleCenterTxt(getString(R.string.acupoint_edit));
        changeBtnState(tVoice, StateOFF);
        changeBtnState(tTemplate, StateOFF);
        changeBtnState(tFormula, StateNone);
        changeBtnState(tTakephoto, StateNone);
        initTemplateAdapter();

        //针灸穴位列表
        listAcup = new ArrayList<>();
        adapterAcup = new AdapterAcupoint(listAcup);
        View inflate = View.inflate(this, R.layout.lay_empty_acupoint, null);
        inflate.setOnClickListener(v -> aboutFunctionArea(FunAcuBoth));
        adapterAcup.setEmptyView(inflate);
        MyGridLayoutManager myGridLayoutManager = new MyGridLayoutManager(context, 4);
        myGridLayoutManager.setScrollEnabled(false);
        rc.setLayoutManager(myGridLayoutManager);
        rc.addItemDecoration(new MySpaceDecoration(JUtils.dip2px(10)));
        rc.setAdapter(adapterAcup);

        //自动补全列表
        autoList = new ArrayList<>();
        autoAdapter = new AdapterAuto(autoList);
        TextView autoInflate = (TextView) View.inflate(this, R.layout.lay_empty_acupoint, null);
        autoInflate.setText("没有符合的穴位");
        autoAdapter.setEmptyView(autoInflate);
        autoRc.addItemDecoration(new MyDividerDecoration(Color.TRANSPARENT, JUtils.dip2px(10)));
        autoRc.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        autoRc.setAdapter(autoAdapter);
        // 床位
        bedBeans = new ArrayList<>();
        bedAdapter = new BedAdapter(this, bedBeans);
        TextView bedEmpty = (TextView) View.inflate(this, R.layout.lay_empty_acupoint, null);
        //   bedEmpty.setText("暂无床位");
        // bedAdapter.setEmptyView(bedEmpty);
        bedRec.addItemDecoration(new MyDividerDecoration(Color.TRANSPARENT, JUtils.dip2px(10)));
        bedRec.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        bedRec.setAdapter(bedAdapter);

        bedAdapter.addOnRecyclerViewLisener(new OnRecyclerViewListener() {
            @Override
            public void onItemClick(View view, int position) {
                BedBean bedBean = bedAdapter.getDataList().get(position);
                if (bedBean.getFldState() == BedType.ENABEL_YES) {
                    if (bedBean.getaBoolean()) {
                        bedBean.setaBoolean(false);
                    } else {
                        bedBean.setaBoolean(true);
                    }
                    bedAdapter.notifyDataSetChanged();
                }
            }

        });

        rootLay.setOnTouchListener(this);
        edtMain.setOnTouchListener(this);
        autoEdt.setOnTouchListener(this);
        MyUtil.getInstance().disableShowSoftInput(autoEdt);
        //非新增才请求治疗信息（病历 元素ID不为0，或者从治疗管理（患者治疗状态不为-1）进入）
        if (eId != 0 || fldTreatmentState != -1) {
            getInfo();
        } else {
            tv_surplus_count.setText(String.valueOf(treatmentNumber));
            tv_previous.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.ic_edit_acupoint_previous, 0, 0);
            tv_next.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.ic_edit_acupoint_next, 0, 0);
        }
        getBedData();
    }

    private void getBedData() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fldDoctorId", fldDoctorId);
        jsonObject.addProperty("flePatientId", fldPatientId);
        UHttp.start(getServes().queryBedInfo(jsonObject), "查询患者治疗信息(床位信息查询)", new HttpMsgListener<ResultBean<List<BedBean>>>() {

            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                showNotice(describe);
            }

            @Override
            public void onFinish() {
            }

            @Override
            public void onSuccess(ResultBean<List<BedBean>> dto) {
                if (dto.isSuccess()) {
                    List<BedBean> bedBeans = dto.getResult();
                    if (bedBeans != null) {
                        bedAdapter.replaceData(bedBeans);
                    }
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        if (view.getId() == autoEdt.getId()) {
            aboutFunctionArea(FunAcu);
        } else if (view.getId() == edtMain.getId()) {
            aboutFunctionArea(FunAcuOthers);
        } else {
            aboutFunctionArea(FunAcuHide);
        }
        return true;
    }

    @Override
    protected void onTemplateSelect(String content) {
        edtMain.append(content);
    }

    @Override
    protected void logic() {
        adapterAcup.setOnItemClickListener((adapter, view, position) -> {
            if (position < 0 || position >= listAcup.size()) {
                showNotice("数据异常");
                return;
            }
            AcupointBean acupoint = listAcup.get(position);
            int fldMeridianLocation = acupoint.getFldMeridianLocation();
            if (fldMeridianLocation == 3) {
                showNotice("该穴位为单侧穴位");
                return;
            }

            if (acupoint.getFldAcupointId() == acupoint.SI_SHEN_CONG_ID) {
                acupointNumber += 4;
                acupoint.setFldAcupointType(4);
            } else {
                int fldAcupointType = acupoint.getFldAcupointType();//双侧 = 0,左侧 = 1,右侧 = 2,单侧 = 3，多册=4
                switch (fldAcupointType) {
                    case 0:
                        fldAcupointType++;
                        acupointNumber--;
                        break;
                    case 1:
                        fldAcupointType++;
                        break;
                    case 2:
                        fldAcupointType = 0;
                        acupointNumber++;
                        break;
                }
                acupoint.setFldAcupointType(fldAcupointType);
            }
            listAcup.set(position, acupoint);
            adapterAcup.notifyItemChanged(position);
            tCont.setText(String.valueOf(acupointNumber));
        });

        adapterAcup.setOnItemLongClickListener((adapter, view, position) -> {
            if (position < 0 || position >= listAcup.size()) {
                showNotice("数据异常");
                return true;
            }
            UDialog.getInstance(context, true, true)
                    .showNoticeWithTwobtn("删除该穴位？", (result, dia) -> {
                        AcupointBean acupointBean = listAcup.get(position);
                        listAcup.remove(position);
                        adapterAcup.notifyItemRemoved(position);
                        int fldAcupointType = acupointBean.getFldAcupointType();
                        if (acupointBean.getFldAcupointId() == acupointBean.SI_SHEN_CONG_ID) {
                            acupointNumber -= 4;
                        } else {
                            if (fldAcupointType == 0) {//双侧
                                acupointNumber -= 2;
                            } else {
                                acupointNumber -= 1;
                            }
                        }

                        tCont.setText(acupointNumber + "");
                        dia.dismiss();
                    });
            return true;
        });
        autoAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (position > -1 && position < autoList.size()) {
                DbAcupoint acupoint = autoList.get(position);
                if (acupoint == null || UTxt.isEmpty(acupoint.getFldAcupointName())) {
                    return;
                }
                int id = acupoint.getId();
                for (AcupointBean acupointBean : listAcup) {
                    if (acupointBean.getFldAcupointId() == id) {
                        showNotice("该穴位已经添加过了");
                        return;
                    }
                }
                int fldMeridianLocation = acupoint.getFldMeridianLocation();
                listAcup.add(new AcupointBean(id, acupoint.getFldAcupointName(), fldMeridianLocation, fldMeridianLocation));
                adapterAcup.notifyDataSetChanged();
                if (acupoint.getId() == AcupointBean.SI_SHEN_CONG_ID) {
                    // 四神聪加四
                    acupointNumber += 4;
                } else {
                    if (fldMeridianLocation == 0) {//双侧
                        acupointNumber += 2;
                    } else {//单侧
                        acupointNumber += 1;
                    }
                }
                tCont.setText(String.valueOf(acupointNumber));
                autoEdt.setText("");
            }
        });
        autoEdt.addTextChangedListener(new KTextWatcher() {
            @Override
            public void afterTextChanged(Editable txtEnd) {
                if (handler.hasMessages(what_code)) {
                    handler.removeMessages(what_code);
                }
                Message msg = handler.obtainMessage();
                msg.what = what_code;
                handler.sendMessageDelayed(msg, 200);//延迟200毫秒
            }
        });
        autoEdt.setOnFocusChangeListener((view, b) -> changeKView(b));
        edtMain.setOnFocusChangeListener((view, b) -> {
            if (b) {
                editAcupoint = false;
            }
        });
        keyboardView.setKeyboardDigitListener(new KKeyboardView.TextListener() {
            @Override
            public void onTextClick(String text) {
                autoEdt.append(text);
            }

            @Override
            public void OnDelClick() {
                String s = autoEdt.getText() + "";
                int length = s.length();
                if (length == 0) {
                    return;
                }
                autoEdt.setText(s.substring(0, length - 1));
                autoEdt.setSelection(length - 1);
            }

            @Override
            public void OnCompleteClick() {
            }

            @Override
            public void OnCancleClick() {
            }
        });
        seekBar.setOnProgressChangedListener(new KBubbleSeekBar.OnProgressChangedListener() {
            @Override
            public void onProgressChanged(KBubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {
                if (progress == 0) {
                    iv_start.setBackgroundResource(R.mipmap.ic_edit_acupoint_srart);
                } else {
                    iv_start.setBackgroundResource(R.mipmap.ic_edit_acupoint_srart_ch);
                }
                if (cureing) {
                    fldTreatmentDuration = (int) (progress + delta);
                    tv_total_time.setText(String.valueOf(fldTotalDuration + fldTreatmentDuration - fldTreatmentDuration_old));
                } else {
                    tTimeRemaining.setText(progress + ":00");
                    if (fldTreatmentState == 2) {
                        tv_total_time.setText(String.valueOf(fldTotalDuration - fldTreatmentDuration_old + progress));
                    } else {
                        tv_total_time.setText(String.valueOf(progress));
                    }
                }
                if (seekBar.isLock()) {
                    long total = progress + delta;
                    seekBar.setSecondProgress(total > 70 ? 70 : total);
                }
            }

            @Override
            public void getProgressOnActionUp(KBubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {
            }

            @Override
            public void getProgressOnFinally(KBubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {
            }
        });
        Selection.setSelection(edtMain.getText(), edtMain.length());
    }


    @Override
    protected void onSpeakClick() {
        if (editAcupoint) {
            autoEdt.setText("");
        }
    }

    @Override
    protected void onFunctionBtnClick(int state) {
        int oldTemplateType = templateType;
        if (editAcupoint) {
            templateType = 4401;
            changeKView(false);
        } else {
            templateType = 4402;
            autoList.clear();
            autoAdapter.notifyDataSetChanged();
            autoEdt.setText("");
        }
        switch (state) {
            case FunTemplate://模板
                if (oldTemplateType != templateType) {
                    spv.callFreshDelay(500);
                }
                break;
            case FunVoice://语音
                if (editAcupoint) {
                    aboutFunctionArea(FunAcuVoice);
                }
                break;
        }
    }

    @Override
    protected void onSpeakBack(String result) {
        if (editAcupoint) {
            int index = autoEdt.getSelectionStart();
            Editable edit = autoEdt.getEditableText();
            if (index < 0 || index >= edit.length()) {
                autoEdt.append(result.replace("。", "").replace("？", "".replace("！", "")));
            } else {
                edit.insert(index, result);
            }
        } else {
            int index = edtMain.getSelectionStart();
            Editable edit = edtMain.getEditableText();
            if (index < 0 || index >= edit.length()) {
                edtMain.append(result);
            } else {
                edit.insert(index, result);
            }
        }
    }

    /**
     * 关于功能区域
     */
    private void aboutFunctionArea(int sw) {
        switch (sw) {
            case FunAcuHide://因此所有
                layFunction.setVisibility(View.GONE);
                autoList.clear();
                autoAdapter.notifyDataSetChanged();
                autoEdt.setText("");
                hideAllKey();
                break;
            case FunAcu://键盘输入穴位
                layFunction.setVisibility(View.VISIBLE);
                UKeyboard.with(this).hideForce(edtMain);
                changeKView(true);
                hideAllFun();
                break;
            case FunAcuVoice://语音输入穴位
                layFunction.setVisibility(View.VISIBLE);
                UKeyboard.with(this).hideForce(edtMain);
                //隐藏自定义键盘
                editAcupoint = true;
                lay_auto.setVisibility(View.VISIBLE);
                keyboardView.hide();
                break;
            case FunAcuOthers://隐藏键盘
              /*  layFunction.setVisibility(View.VISIBLE);
                hideAllKey();*/

                break;
            case FunAcuBoth:
                layFunction.setVisibility(View.VISIBLE);
                UKeyboard.with(this).hideForce(edtMain);
                if (!lay_auto.isShown()) {
                    autoList.clear();
                    autoAdapter.notifyDataSetChanged();
                    autoEdt.setText("");
                    changeKView(true);
                }
                hideAllFun();
                break;
        }

    }

    @OnClick({R.id.title_next_txt, R.id.iv_start, R.id.tv_continue, R.id.rec_edt_lay,
            R.id.rec_acu_rc_lay, R.id.lay_rec_fun_result, R.id.lay_rec_fun_lay, R.id.tv_records, R.id.tv_cure_list})
    public void onClicked(View view) {
        int progress = seekBar.getProgress();
        String content = edtMain.getText().toString();
        switch (view.getId()) {
            case R.id.rec_acu_rc_lay://穴位选择:
                aboutFunctionArea(FunAcuBoth);
                break;
            case R.id.rec_edt_lay://其他治疗输入:
                aboutFunctionArea(FunAcuOthers);
                break;
            case R.id.lay_rec_fun_result://穴位检索输入:
                changeKView(true);
                break;
            case R.id.title_next_txt://保存:
                if (listAcup.size() == 0) {
                    showNotice("还未选择穴位");
                    return;
                }
                if (progress == 0) {
                    showNotice("治疗时长不能为0");
                    return;
                }
                hideAllKey();
                save(2, progress, content);//开始治疗 = 0,继续接诊 = 1,保存 = 2
                break;
            case R.id.iv_start://开始治疗:
                if (listAcup.size() == 0) {
                    showNotice("还未选择穴位");
                    return;
                }
                if (progress == 0) {
                    showNotice("治疗时长不能为0");
                    return;
                }
                hideAllKey();
                save(0, progress, content);//开始治疗 = 0,继续接诊 = 1,保存 = 2
                break;
            case R.id.tv_continue://继续接诊:
                if (listAcup.size() == 0) {
                    showNotice("还未选择穴位");
                    return;
                }
                if (progress == 0) {
                    showNotice("治疗时长不能为0");
                    return;
                }
                hideAllKey();
                save(1, progress, content);//开始治疗 = 0,继续接诊 = 1,保存 = 2
                break;
            case R.id.tv_records:
                Intent intent = new Intent(context, RecordEditActivity.class);
                intent.putExtra(Code.SP.ID, fldMedicalHistoryId);
                startActivity(intent);
                break;
            case R.id.tv_cure_list:
                startActivity(new Intent(context, MainActivity.class));
                sendBroadcast(new Intent(Code.Broadcast.CutoverToCure));
                break;
        }
    }

    @Override
    protected void hideInputAll() {
        changeKView(false);
    }

    /**
     * 隐藏所以输入区域
     */
    private void hideAllKey() {
        UKeyboard.with(this).hideForce(edtMain);
        changeKView(false);
        hideAllFun();
    }


    /**
     * @param show 显示/隐藏自定义键盘
     */
    private void changeKView(boolean show) {
        if (show) {
            editAcupoint = true;
            autoEdt.requestFocus();
            autoEdt.postDelayed(() -> {
                keyboardView.show();
                lay_auto.setVisibility(View.VISIBLE);
            }, 400);
        } else {
            keyboardView.hide();
            lay_auto.setVisibility(View.GONE);
        }
    }

    private void save(int treatmentOperation, int progress, String content) {
        ProgressDialog.getInstance().startProgressDialog(this);
        String other = other_text.getText().toString().trim();
        Map<String, Object> map = new HashMap<>();
        map.put("fldMedicalHistoryId", fldMedicalHistoryId);
        map.put("fldEditId", SPUtil.getUserId());
        map.put("fldDoctorId", fldDoctorId);
        //TODO 未完成
    /*    map.put("fldBedId", bedAdapter.selectPosition == -1 ? null : bedAdapter.getItem(bedAdapter.selectPosition).getFldBedId());
        map.put("fldBedNum", bedAdapter.selectPosition == -1 ? null : bedAdapter.getItem(bedAdapter.selectPosition).getFldBedNum());*/

        if (fldTreatmentState == 1) {
            map.put("fldTreatmentDuration", progress + delta);
        } else {
            map.put("fldTreatmentDuration", progress);
        }
        map.put("fldDurationUnit", 1);
        map.put("fldTreatmentDesc", other);
        map.put("treatmentOperation", treatmentOperation);//开始治疗 = 0,继续接诊 = 1,保存 = 2
        map.put("patientTreatmentAcupoint", listAcup);
        UHttp.start(getServes().cureStart(map), "添加患者治疗(开始治疗/继续接诊/保存)", new HttpMsgListener<ResultBean<RecordWebBean
                .MedicalElementBean>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                showNotice(describe);
            }

            @Override
            public void onFinish() {
                ProgressDialog.getInstance().stopProgressDialog();
            }

            @Override
            public void onSuccess(ResultBean<RecordWebBean.MedicalElementBean> dto) {
                if (dto.isSuccess()) {
                    RecordWebBean.MedicalElementBean medicalElementBean = dto.getResult();
                    if (medicalElementBean != null) {
                        if (treatmentOperation == 0) {//开始治疗 = 0,继续接诊 = 1,保存 = 2
                            startActivity(new Intent(context, MainActivity.class));
                            sendBroadcast(new Intent(Code.Broadcast.CutoverToCure));
                        } else if (treatmentOperation == 1) {
                            startActivity(new Intent(context, MainActivity.class));
                            sendBroadcast(new Intent(Code.Broadcast.CutoverToReception));
                        } else {
                            UToast.toast("保存成功");
                            Intent intent = getIntent();
                            intent.putExtra(Code.SP.CONTENT, medicalElementBean.getFldElementValue());
                            intent.putExtra(Code.SP.ID, medicalElementBean.getId());
                            setResult(Activity.RESULT_OK, intent);
                            finish();
                            sendBroadcast(new Intent(Code.Broadcast.CutoverToCure));
                        }
                    }
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        String errorMessage = UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt);
                        if ("没有次数了！".equals(errorMessage)) {
                            UDialog.getInstance(context, true, false)
                                    .showNoticeWithTwobtn("患者" + fldPatientName + "的针灸次数为[0]，是否增加针灸次数？", "取消", "确定", (result, dia) -> {
                                        Intent intent = new Intent(context, SurplusCureActivity.class);
                                        intent.putExtra(Code.SP.ID, fldPatientId);
                                        startActivity(intent);
                                        dia.dismiss();
                                    });
                        } else {
                            showNotice(errorMessage);
                        }
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    private void getInfo() {
        ProgressDialog.getInstance().startProgressDialog(this);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fldMedicalHistoryId", fldMedicalHistoryId);
        UHttp.start(getServes().queryCureInfo(jsonObject), "查询患者治疗信息(针灸方案)", new HttpMsgListener<ResultBean<CureInfo>>() {

            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                showNotice(describe);
            }

            @Override
            public void onFinish() {
                ProgressDialog.getInstance().stopProgressDialog();
            }

            @Override
            public void onSuccess(ResultBean<CureInfo> dto) {
                if (dto.isSuccess()) {
                    CureInfo cureInfo = dto.getResult();
                    if (cureInfo != null) {
                        acupointNumber = cureInfo.getAcupointNumber();
                        fldTreatmentState = cureInfo.getFldTreatmentState();
                        String fldTreatmentStart = cureInfo.getFldTreatmentStart();
                        fldTreatmentDuration = cureInfo.getFldTreatmentDuration();
                        fldTreatmentDuration_old = fldTreatmentDuration;
                        fldTotalDuration = cureInfo.getFldTotalDuration();
                        String fldTreatmentDesc = cureInfo.getFldTreatmentDesc();
                        int fldAcupunctureFrequency = cureInfo.getFldAcupunctureFrequency();
                        showInfo(fldTreatmentStart, fldTreatmentDesc, fldAcupunctureFrequency);
                        showPreviousOrNext();
                        List<AcupointBean> patientTreatmentInfoAcupoint = cureInfo.getPatientTreatmentInfoAcupoint();
                        listAcup.clear();
                        if (!UTxt.isEmpty(patientTreatmentInfoAcupoint)) {
                            listAcup.addAll(patientTreatmentInfoAcupoint);
                        }
                        adapterAcup.notifyDataSetChanged();
                    }
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    private void showPreviousOrNext() {
        ArrayList<PatientListBean.ItemsBean> cureList = (ArrayList<PatientListBean.ItemsBean>) CacheDiskUtils.getInstance().getSerializable(getIntent().getStringExtra(DATA_LIST_KEY));
        int fldLastMedicalHistoryId = 0, fldNextMedicalHistoryId = 0;
        PatientListBean.ItemsBean previousPatient = null, nextPatient = null;
        for (int position = 0; position < cureList.size(); position++) {
            PatientListBean.ItemsBean itemsBean = cureList.get(position);
            if (itemsBean.getFldMedicalHistoryId() == fldMedicalHistoryId) {
                try {
                    previousPatient = cureList.get(position - 1);
                    fldLastMedicalHistoryId = previousPatient.getFldMedicalHistoryId();
                } catch (Exception e) {
                    //以上是骚操作
                }
                try {
                    nextPatient = cureList.get(position + 1);
                    fldNextMedicalHistoryId = nextPatient.getFldMedicalHistoryId();
                } catch (Exception e) {
                    //以上是骚操作
                }
                break;
            }
        }
        if (fldLastMedicalHistoryId != 0) {
            tv_previous.setClickable(true);
            tv_previous.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.ic_edit_acupoint_previous_ch, 0, 0);
            int finalFldLastMedicalHistoryId = fldLastMedicalHistoryId;
            PatientListBean.ItemsBean finalPreviousPatient = previousPatient;
            tv_previous.setOnClickListener(view -> {
                fldMedicalHistoryId = finalFldLastMedicalHistoryId;
                fldDoctorId = finalPreviousPatient.getFldDoctorId();
                fldPatientId = finalPreviousPatient.getFldPatientId();
                getInfo();
                showInfo(finalPreviousPatient.getFldPatientName(), finalPreviousPatient.getFldPatientSex(), finalPreviousPatient
                        .getFldAge(), finalPreviousPatient.getFldCreateTime(), finalPreviousPatient.getFldMedicalNum(), finalPreviousPatient
                        .getFldCustomerName(), "");
            });
        } else {
            tv_previous.setClickable(false);
            tv_previous.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.ic_edit_acupoint_previous, 0, 0);
        }
        if (fldNextMedicalHistoryId != 0) {
            tv_next.setClickable(true);
            tv_next.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.ic_edit_acupoint_next_ch, 0, 0);
            int finalFldNextMedicalHistoryId = fldNextMedicalHistoryId;
            PatientListBean.ItemsBean finalNextPatient = nextPatient;
            tv_next.setOnClickListener(view -> {
                fldMedicalHistoryId = finalFldNextMedicalHistoryId;
                fldDoctorId = finalNextPatient.getFldDoctorId();
                fldPatientId = finalNextPatient.getFldPatientId();
                getInfo();
                showInfo(finalNextPatient.getFldPatientName(), finalNextPatient.getFldPatientSex(), finalNextPatient
                        .getFldAge(), finalNextPatient.getFldCreateTime(), finalNextPatient.getFldMedicalNum(), finalNextPatient
                        .getFldCustomerName(), "");
            });
        } else {
            tv_next.setClickable(false);
            tv_next.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.ic_edit_acupoint_next, 0, 0);
        }
    }

    private void showInfo(String fldTreatmentStart, String fldTreatmentDesc, int fldAcupunctureFrequency) {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
        long surplus;//剩余时长(分钟)
        if (fldTreatmentState == 1) {//患者治疗状态，0：无状态，1：治疗中，2：治疗完
            Date date = UDate.strToDateSafety(fldTreatmentStart);
            delta = (System.currentTimeMillis() - date.getTime()) / 1000 / 60;//已过时长（分钟）
            surplus = fldTreatmentDuration - delta;//剩余时长(分钟)
            if (delta >= fldTreatmentDuration) {//已过时长大于等于治疗时长，则将已过时长改为等于治疗时长，剩余时长改为0
                cureing = false;
                delta = fldTreatmentDuration;
                surplus = 0;
            } else {
                cureing = true;
                gogogo(fldTreatmentStart);
                Observable.interval(1000, TimeUnit.MILLISECONDS)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new MyObserver<Long>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                                disposable = d;
                                addEvent(d);
                            }

                            @Override
                            public void onNext(Long aLong) {
                                gogogo(fldTreatmentStart);
                            }
                        });
            }
        } else {
            cureing = false;
            delta = 0;
            surplus = fldTreatmentDuration;
        }
        seekBar.setDelta(delta);
        seekBar.setProgress(surplus);
        seekBar.setLocked(true);
        seekBar.setSecondProgress(fldTreatmentDuration);
        tv_total_time.setText(String.valueOf(fldTotalDuration));
        tv_surplus_count.setText(String.valueOf(fldAcupunctureFrequency));
        tCont.setText(String.valueOf(acupointNumber));
        edtMain.setText(fldTreatmentDesc);
        Selection.setSelection(edtMain.getText(), edtMain.length());
    }

    private void gogogo(String fldTreatmentStart) {
        Date date = UDate.strToDateSafety(fldTreatmentStart);
        //剩余时长(秒)
        long surplusSecond = date.getTime() / 1000 + fldTreatmentDuration * 60 - System.currentTimeMillis() / 1000;
        if (surplusSecond < 1) {
            if (disposable != null && !disposable.isDisposed()) {
                disposable.dispose();
            }
            fldTreatmentState = 2;
            cureing = false;
            seekBar.setProgress(0);
            tTimeRemaining.setText("0:00");
            return;
        }
        long minutes = surplusSecond / 60;
        long seconds = surplusSecond % 60;
        if (seconds == 0) {
            seekBar.setProgress(minutes + 1);
        }
        String m = minutes < 10 ? "0" + minutes : minutes + "";
        String s = seconds < 10 ? "0" + seconds : seconds + "";
        tTimeRemaining.setText(m + ":" + s);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (!keyboardView.isShown()) {
            finish();
        } else {
            keyboardView.hide();
        }
    }

    @Override
    public void cureEnd(String content) {
        if (!TextUtils.isEmpty(edtMain.getText())) {
            content += ",其他治疗：" + edtMain.getText();
        }
        super.cureEnd(content);
    }
}
